$NG.AllReady(function (page, { useAction, useBeforeClick, useValuesChange, useClick, useUpdateRow, subscribe, useUpdateRows }) {
    const mstform = $NG.getCmpApi("p_form_gctzch_m")
    let dgrid1 = $NG.getCmpApi("p_form_gctzch_d2")
    let dgrid2 = $NG.getCmpApi("p_form_gctzch_d3")
    const getHeadValue = (str) => mstform.getItem(str).getValue()
    
    const param = parseUrlParams(location.href)

    const config = {
        saveLock:false
    }

    if (param.sourceid && !mstform.getItem("u_lyid").getValue()) {
        mstform.getItem("u_lyid").setValue(param.sourceid)
    }
    selectTabs('1')

    const saves = ['save', 'check']

    saves.forEach(item=>{
        useBeforeClick(()=>{
            if(config.saveLock){
                $NG.alert("当前项目策划已经含有收尾策划，不可新增！")
                return false
            }
        },item)
    })


    useValuesChange(() => {
        selectTabs('1')
        isTabs()
        hiddenAttmentch()
    }, "p_form_gctzch_m.u_chzt")

    useValuesChange(()=>{
        getXmchByPhid()
        getVersion()
        getSwFrom()
    },"p_form_gctzch_m.u_chmc")

    useUpdateRows(({args})=>{
        const rows = dgrid1.getRows()
        let u_qrdyysr = 0
        let u_gcjsje = 0
        let u_gsglf = 0
        let u_fgsglf = 0
        let u_lrze = 0
        let u_lrl = 0
        rows.forEach(el=>{
            el.s_tree_name = el.s_tree_name.replaceAll(" ","")
            console.log(el.s_tree_name,el.s_tree_name == '公司');
            if(el.s_tree_name.includes("营业收入")){
                u_qrdyysr += (Number(el.u_je) || 0)
            } 
            if(el.s_tree_name.includes("工程结算金额")){
                u_gcjsje += (Number(el.u_je) || 0)
            } 
            if(el.s_tree_name == '公司'){
                console.log(`设置公司`,);
                u_gsglf += (Number(el.u_je) || 0)
            } 
            if(el.s_tree_name == '分公司'){
                u_fgsglf += (Number(el.u_je) || 0)
            } 
            if(el.s_tree_name == '利润总额'){
                u_lrze += (Number(el.u_je) || 0)
            } 
            if(el.s_tree_name.includes('利润率')){
                u_lrl += (Number(el.u_je) || 0)
            }
        })
        mstform.getItem("u_qrdyysr").setValue(u_qrdyysr)
        mstform.getItem("u_gcjsje").setValue(u_gcjsje)
        mstform.getItem("u_gsglf").setValue(u_gsglf)
        mstform.getItem("u_fgsglf").setValue(u_fgsglf)
        mstform.getItem("u_lrze").setValue(u_lrze)
        mstform.getItem("u_lrl").setValue(u_lrl)
        dgrid1.refreshView()
    },"p_form_gctzch_d2")

    useUpdateRows(({args})=>{
        const rows = dgrid2.getRows()
        let u_hte = 0
        let u_yysrbhbyj = 0
        let u_zcb = 0
        let u_fgsglfwy = 0
        let u_gsglfwy = 0
        let u_lr = 0
        let u_lrl_ = 0
        rows.forEach(el=>{
            el.s_tree_name = el.s_tree_name.replaceAll(" ","")
            if(el.s_tree_name.includes("合同金额")){
                u_hte += (Number(el.u_je) || 0)
            } else if(el.s_tree_name == '营业收入'){
                u_yysrbhbyj += (Number(el.u_je) || 0)
            } else if(el.s_tree_name == '成本预测'){
                u_zcb += (Number(el.u_je) || 0)
            } else if(el.s_tree_name == '分公司'){
                u_fgsglfwy += (Number(el.u_je) || 0)
            } else if(el.s_tree_name == '公司'){
                u_gsglfwy += (Number(el.u_je) || 0)
            }  else if(el.s_tree_name.includes('利润率')){
                el.u_je = u_je / u_hte
                u_lrl_ += (Number(el.u_je) || 0)
            } else if(el.s_tree_name.includes('利润')){
                el.u_je = u_hte - u_zcb
                u_lr += (Number(el.u_je) || 0)
            }
        })
        mstform.getItem("u_hte").setValue(u_hte)
        mstform.getItem("u_yysrbhbyj").setValue(u_yysrbhbyj)
        mstform.getItem("u_zcb").setValue(u_zcb)
        mstform.getItem("u_fgsglfwy").setValue(u_fgsglfwy)
        mstform.getItem("u_gsglfwy").setValue(u_gsglfwy)
        mstform.getItem("u_lr").setValue(u_lr)
        mstform.getItem("u_lrl_").setValue(u_lrl_)
        dgrid2.refreshView()
    },"p_form_gctzch_d3")

    function isTabs() {
        const bo = mstform.getItem("u_chzt").getValue()
        if (bo == '01') {
            selectTabs("tabPanel_tabItem,tabPanel_tabItem_1")
        } else {
            selectTabs('1')
        }
        setTimeout(() => {
            dgrid1 = $NG.getCmpApi("p_form_gctzch_d2")
            dgrid2 = $NG.getCmpApi("p_form_gctzch_d3")
        }, 200)
    }
    // 进场策划调整
    function selectTabs(key) {
        const u_chzt = getHeadValue("u_chzt")
        const tabs = $NG
            .getCompMap()
            .get("__Tabs__")[0]
            .getApi();

        tabs.updateItems((innerItems, activeKey) => {
            return [...innerItems.filter((item) => {
                if (key.split(",").includes(item.name)) {
                    return item
                }
            })];
        });
        setTimeout(() => {
            if (key != '1') {
                dgrid1 = $NG.getCmpApi("p_form_gctzch_d2")
                dgrid2 = $NG.getCmpApi("p_form_gctzch_d3")
                $NG.execServer("SELECT", {
                    sql: `select s_tree_id,
             s_tree_no, s_tree_name, s_tree_pid, u_dw, u_je,u_bz from p_form_gctzchjcb_d1`}, (res) => {
                    if (res.count == 0) return
                    const datas = JSON.parse(res.data).reduce((value, item) => {
                        value.push(item.extendObjects)
                        return value
                    }, [])
                    const arr = arrayToTree(datas, "s_tree_id", "s_tree_pid")
                    dgrid1.clearRows().then(() => {
                        dgrid1.addRows(arr)
                    })
                })
                $NG.execServer("SELECT", {
                    sql: `select s_tree_id,
             s_tree_no, s_tree_name, s_tree_pid, u_dw, u_je,u_bz from p_form_gctzchjcb_d2`}, (res) => {
                    if (res.count == 0) return
                    const datas = JSON.parse(res.data).reduce((value, item) => {
                        value.push(item.extendObjects)
                        return value
                    }, [])
                    const arr = arrayToTree(datas, "s_tree_id", "s_tree_pid")
                    dgrid2.clearRows().then(() => {
                        dgrid2.addRows(arr)
                    })
                })
            }
        }, 200)
    }

    // 获取项目策划信息
    function getXmchByPhid(){
        const phid = getHeadValue("u_chmc")
        if(!phid) return 
        $NG.execServer("getXmchByPhid",{phid},(res)=>{
            if(res.count == 0) return 
            const datas = JSON.parse(res.data)[0].extendObjects
            const arr = [
                {
                    key:"u_xmmc",
                    value:{
                        label:datas.u_xmmc_exname,
                        value:datas.u_xmmc
                    }
                },
                {
                    key:"u_htmc",
                    value:{
                        label:datas.u_htmc_exname,
                        value:datas.u_htmc
                    }
                },
                {
                    key:"u_zbrq",
                    value:datas.u_zbrq
                },
                {
                    key:"u_htqdsj",
                    value:datas.u_htqdrq
                },
                {
                    key:"u_gq",
                    value:datas.u_htrq
                },
                {
                    key:"u_htje",
                    value:datas.u_htje
                },
                {
                    key:"u_chzt",
                    value:datas.u_chzt
                },

            ]
        setHeadValue(arr)
        })
    }

    // 隐藏Attachment
    // 隐藏附件
    function hiddenAttmentch() {
        const u_chzt = mstform.getItem("u_chzt").getValue()
        const temp = ["u_htjdxgwj", "u_xmchxgwj", "u_swchxgwj",]
        if (!u_chzt) {
            temp.forEach(el => {
                $NG.updateUI((updater) => {
                    updater.fieldSetForm.p_form_gctzch_m[el].setProps({
                        hidden: true
                    })
                })
            })
        } else if (u_chzt == '01') {
            temp.forEach(el => {
                $NG.updateUI((updater) => {
                    updater.fieldSetForm.p_form_gctzch_m[el].setProps({
                        hidden: el == 'u_swchxgwj'
                    })
                })
            })
        } else if (u_chzt == '02') {
            temp.forEach(el => {
                $NG.updateUI((updater) => {
                    updater.fieldSetForm.p_form_gctzch_m[el].setProps({
                        hidden: el !== 'u_swchxgwj'
                    })
                })
            })
        }
    }


    // 获取版本号
    function getVersion(){
        const currentPhid = mstform.getValues().phid || '0'
        const phid = getHeadValue("u_chmc")
        $NG.execServer("SELECT",{sql:`select phid from p_form_gctzch_m where phid != ${currentPhid}`},(res)=>{
            mstform.getItem("u_bbh").setValue(res.count)
        })
    }
// 检查是否做过收尾
    function getSwFrom(){
        const phid = getHeadValue("u_chmc")
        if(!phid) return 
        $NG.execServer(`SELECT`,{sql:`select phid from p_form_gctzch_m where u_chmc = '${phid}' and u_chzt = '02'`},(res)=>{
            if(res.count != 0 ){
                config.saveLock = true
                $NG.alert("当前项目策划已经含有收尾策划，不可新增！")
            } else{
                config.saveLock = false

            }
        })
    }

    // 转属性结构
    function arrayToTree(items, idField = "id", parentField = "parentId", childrenField = "children") {
        const map = {};
        const roots = [];
``
        // 先建立 id → item 的映射
        items.forEach(item => {
            map[item[idField]] = { ...item, [childrenField]: [] };
        });

        // 组装树
        items.forEach(item => {
            const parentId = item[parentField];
            if (parentId == null || parentId.length < 2 || parentField == '0') {
                // 根节点
                roots.push(map[item[idField]]);
            } else if (map[parentId]) {
                // 挂到父节点的 children 上
                map[parentId][childrenField].push(map[item[idField]]);
            }
        });

        return roots;
    }
    // 添加明细
    function parseUrlParams(url) {
        // 分离URL的哈希部分
        const hashIndex = url.indexOf('#');
        if (hashIndex === -1) return {};

        const hashPart = url.substring(hashIndex + 1);

        // 分离哈希路径和查询参数
        const questionMarkIndex = hashPart.indexOf('?');
        if (questionMarkIndex === -1) return {};

        const queryString = hashPart.substring(questionMarkIndex + 1);

        // 解析查询参数
        const params = {};
        queryString.split('&').forEach(param => {
            const [key, value] = param.split('=');
            if (key && value !== undefined) {
                params[key] = decodeURIComponent(value);
            }
        });

        return params;
    }

    // 赋值
    function setHeadValue(datas) {
        datas.forEach(item => {
            try {
                mstform.getItem(item.key).setValue(item.value)
            } catch (err) {
                console.log(`err`, err, item);
            }
        })
    }
})